<template>
  <div>
    <basic-container>
      <!-- 头部进度条 -->
      <div class="progress">
        <p>{{formData.goodsCategoryId}}</p>
        <el-steps :active="activeStep" simple>
          <el-step title="基本信息" icon="el-icon-edit"></el-step>
          <el-step title="图文信息" icon="el-icon-upload"></el-step>
        </el-steps>
      </div>
      <div v-show="activeStep == 0">
        <!-- 商品信息 -->
        <avue-form :option="option" v-model="formData">
          <!-- 展示分类 -->
          <template slot-scope="scope" slot="category">
            <avue-input-tree
              :defaultExpandAll="true"
              :dic="goodsCategory"
              :props="defaultProps"
              v-model="formData.categoryId"
              type="tree"
              placeholder="请选择所属分类"

            />
          </template>
          <!-- 商品主图 -->
          <template slot-scope="scope" slot="thumbUrl">
            <div>
              <div v-show="formData.thumbUrl" class="thumbUrl">
                <img :src="formData.thumbUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove"></i>
                  <i class="el-icon-view" @click="handlePicturePreview"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img(1)">
                <i class="el-icon-plus" />
              </div>
              <el-dialog :visible.sync="sleImg" title="选择图片">
                <sel-img-photogallery ref="selImg" :type="'03'" @select="onSelectImgs" >
                </sel-img-photogallery>
              </el-dialog>
              <el-dialog :visible.sync="picturePreviewVisible" title="商品主图">
                <div class="picturePreviewDialog">
                  <img :src="formData.thumbUrl" style="width:100%;height:100%;">
                </div>
              </el-dialog>
            </div>
          </template>
          <!-- 商品轮播图 -->
          <template slot-scope="scope" slot="photoList">
            <div>
              <div v-for="(item,index) in formData.photoList" :key="index" class="thumbUrl">
                <img :src="item.picUrl"/>
                <div class="hover_show">
                  <i class="el-icon-delete" @click="sliderPictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" style="float: left;" @click="sel_img(2)"><i class="el-icon-plus"></i></div>
            </div>
          </template>
          <!-- 价格库存 -->
          <template slot="group2Header">
            <span style="float: left;">
              价格库存
            </span>
          </template>
        </avue-form>
        <!-- 规格表单 -->
        <div class="goods-models-wrap">
          <goods-model-selecter
            ref="goodsModelsComponent"
            :has-model="true"
            :goods-info="formData"
            :type="true"
          ></goods-model-selecter>
        </div>
        <div class="button-group__center">
          <el-button type="default" @click="turnToGoodsList">取消</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </div>
      </div>
      <!-- 图文信息 -->
      <component
        v-if="activeStep == 1"
        :is="'goodsMediaInfo'"
        :goods-info="formData"
        @prev="prevStep"
        @save="saveGoodsBaseInfo"/>
    </basic-container>
  </div>
</template>

<script>
import goodsModelSelecter from './component/goodsModelSelecter'
import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery'
import Request from '../../crm/goods/request'
import { getSliderImage, uploadSliderImages } from '@/api/goods/goods'
import { goodsOption } from '../../const/crud/supply/addsupplygoods'
import goodsMediaInfo from '../../crm/goods/addGoods/components/goodsMediaInfo'
import {getEditInfo} from "../../api/goods/goods"
import {getCategoryTree} from "../../api/goods/goodscategory"
import {changeEditInfo} from '../../api/goods/goods'

export default {
  components: {
    goodsModelSelecter,
    selImgPhotogallery,
    goodsMediaInfo
  },
  data() {
    return {
      formData: {},
      defaultProps: {
        defaultExpandAll: true,
        label: 'name',
        value: 'id',
        children: 'children'
      },
      activeStep: 0,
      option: goodsOption,
      goodsCateLoading: false,
      // 分类选择框
      showCategoryTree: false,
      // 图片上传
      picturePreviewVisible: false,
      pictureList: [],
      sleImg: false,
      sleImgType: 1,
      delImages: [],
      updImages: [],
      sliderImage: [],
      // 规格
      hasModel: true,
      shopId: '',
      goodsCategory: [],
      goodsSn: ''
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.shopId = vm.$route.query.res.shopId;
      vm.goodsSn = vm.$route.query.res.goodsSn;
      vm.getGoodsCategory()
      vm.fetchGoodsInfo(vm.$route.query.res.goodsSn)
    });
  },
  created() {
    console.log(this.formData);
  },
  watch: {
    formData() {
      this.initData()
    }
  },
  mounted() {
    this.initData()
    this.initSlider()

  },
  methods: {
    initData() {
      const formData = this.formData
      if (formData.thumbUrl && this.pictureList.length < 1) {
        this.pictureList.push({
          name: 'cover',
          url: formData.thumbUrl
        })
      }
      if (formData.categoryId) {
        this.defaultChecked = formData.categoryId.split(',')
      }
      this.hasModel = formData.goodsModel > 0 ? true : false
    },
    // 获取商品信息
    fetchGoodsInfo(id) {
      getEditInfo({
        goodsSn: id
      }).then(res => {
        console.log('2');
        if (res.status === 200) {
          this.formData = res.data.data

          console.log(this.formData);
        } else {
          this.$message.error('获取商品信息错误: ', res.msg)
        }
      })
    },
    // 获取分类
    getGoodsCategory() {
      this.goodsCateLoading = true
      this.showCategoryTree = true
      const params = {
        shopId: this.shopId
      }
      getCategoryTree(params).then(res => {
        const data = res.data.data
        this.goodsCateLoading = false
        // data.goodsCategoryId = data.goodsCategoryId ? Number(data.goodsCategoryId) : null;
        this.goodsCategory = data
        console.log(data);
        // this.test = '618'
      })
    },
    // 选择图片
    sel_img(type) {
      if(type == 1) {
        this.sleImg = true
        this.sleImgType = type
      }
      if (this.formData.photoList.length == 5) {
        this.$message.error("轮播最多选择5张")
      } else {
        this.sleImg = true
        this.sleImgType = type
      }
    },
    onSelectImgs(imgs) {
      console.log(imgs);
      if (this.sleImgType == 1) {
        this.formData.thumbUrl = imgs[0].picUrl
        this.sleImg = false
      }
      if (this.sleImgType == 2) {
        let len = imgs.length + this.formData.photoList.length
        const currlen = this.formData.photoList.length
        if (len > 5) {
          // this.$message.error("轮播最多选择5张")
          for(let i=0;i< 5 - currlen;i++) {
            console.log(5 - this.formData.photoList.length);
            this.formData.photoList.push({
              id: imgs[i].id,
              picUrl: imgs[i].picUrl
            })
            this.sleImg = false
          }
        } else {
          imgs.forEach( item => {
            this.formData.photoList.push({id: item.id,picUrl: item.picUrl})
          })
          this.sleImg = false
        }
      }
    },
    // 删除商品主图
    handlePictureRemove() {
      this.formData.thumbUrl = ''
    },
    // 查看商品主图
    handlePicturePreview() {
      this.picturePreviewVisible = true
    }, // 删除el-upload的图片
    sliderPictureRemove(index) {
      // this.delImages.push(this.sliderImage[index].url)
      this.formData.photoList.splice(index, 1)
    },
    // 取消
    turnToGoodsList() {
      this.goBack()
    },
    //返回
    goBack(time = 1000) {
      let that = this;
      setTimeout(function () {
        that.$store.commit('DEL_ONE_TAG', that.$route);
        that.$router.go(-1);
      }, time);
    },
    // 下一步
    nextStep() {
      if (this.formData.goodsName &&
        this.formData.unit &&
        this.formData.categoryId &&
        this.formData.thumbUrl &&
        this.formData.marketPrice &&
        this.formData.storage &&
        this.$refs.goodsModelsComponent.tableData.length != 0
      ) {
        // this.syncModelInfo()
        this.activeStep = 1
      } else {
        if(!this.formData.categoryId) {
          this.$message.error('请选择分类!')
        }
        else if(!this.formData.thumbUrl) {
          this.$message.error('请选择商品主图!')
        }
        else if(this.$refs.goodsModelsComponent.tableData.length == 0) {
          this.$message.error('请填写商品规格')
        }
        else{
          this.$message.error('有必填项未填写!')
        }
      }
    },
    syncModelInfo() {
      const ref = this.$refs.goodsModelsComponent
      if (ref) {
        this.formData.goodsModel = this.hasModel ? '1' : '0'
        // this.formData.modelInfo = ref.selectModels
        // this.formData.goodsModelList = ref.goodsModels
        let modelList = ref.tableData
        let typeName = ref.checkedModels.join()
        modelList.forEach(item => {
          let modelName = item.modelName.join()
          item.modelName = modelName
          item.typeName = typeName
        })
        this.formData.modelList = modelList
        console.log(this.formData);
      } else {
        this.formData.goodsModel = '0'
      }
    },
    // 初始化轮播图
    initSlider() {
      if (this.$route.query && this.$route.query.goodsSn) {
        getSliderImage(this.$route.query.goodsSn).then(res => {
          for (const item of res.data.data) {
            this.sliderImage.push({
              name: 'cover',
              url: item
            })
          }
        })
      }
    },
    // 保存上架
    saveGoodsBaseInfo() {
      if(this.formData.goodsCategoryId == null) {
        const categoryId = this.formData.categoryId
        this.formData.goodsCategoryId = categoryId
      }
      this.syncModelInfo()
      console.log(this.formData);
      changeEditInfo(this.formData).then(res => {
        console.log(res);
        this.$message.success('保存成功')
        this.goBack()
      })
    },
    // 上一步
    prevStep(step) {
      this.activeStep = step
    }
  }
}
</script>

<style lang="scss" scoped>
.progress{
  padding-top: 10px;
  width: 50%;
  margin-top: 10px;
  margin-right: 0;
  margin-left: 0;
  margin: auto
    }
.goods-category {
    border: 1px solid #e9e9e9;
    margin: 10px 0 0 10px;
    width: 286px;
    border-radius: 3px;
    max-height: 300px;
    overflow: scroll;
}
.thumbUrl {
  position: relative;
  width: 150px;
  height: 150px;
  float: left;
  margin-left: 15px;
  line-height: 146px;
  overflow: hidden;
  border-radius: 6px;
  .hover_show {
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    display: none;
    padding-left: 40px;
    i {
      color: #fff;
      margin: 0 10px;
      cursor: pointer;
    }
  }
  img {
    width: 100%;
    height: 100%;
  }
}
.thumbUrl:hover .hover_show{
  display: block;
}
.select_img{
  float: left;
  margin-left: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 148px;
  height: 148px;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  font-size: 28px;
  color: #8c939d;
  cursor: pointer;
  border-radius: 6px;
}
.goods-models-wrap {
  margin: 0 0 50px 40px;
}
.button-group__center {
  display: flex;
  justify-content: center;
}
.tbngroup {
  position: absolute;
  bottom: 50px;
  left: 50%;
}
</style>
